<?php

namespace App\Commons\Services\Payment;

// use App\Commons\Domain\Order\Model\Order;
use EasyWeChat;

/**
 * 微信支付
 */
class WechatPayService
{

    /**
     * [微信统一下单]
     * @author qiumzh
     * @since  2019-09-29
     * @param  string     $body         [description]
     * @param  string     $out_trade_no [description]
     * @param  string     $amount       [description]
     * @param  string     $openid       [description]
     * @return [type]                   [description]
     */
    public function unify(string $body, string $out_trade_no, string $amount, string $openid)
    {
        $pay_data = [
            'body' => $body,
            'out_trade_no' => $out_trade_no,
            // 'total_fee' => $amount * 100,    //单位为 分
            'total_fee' => app()->environment('production') ? _bcmul($amount, 100) : 1,    //单位为 分
            // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            // 'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ];
        //微信统一下单
        $result = EasyWeChat::payment()->order->unify($pay_data);

        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            return EasyWeChat::payment()->jssdk->bridgeConfig($result['prepay_id'], false);
        } else {
            //微信下单失败
            throw_e(array_get($result, 'err_code_des'));
        }
    }

    /**
     * 微信退款
     * @param  Order  $order 订单
     * @return [type]        [description]
     */
    public function refund(Order $order)
    {
        throw_on(in_array(intval($order->status), [0, -1]), '只有已支付订单才能退款');
        throw_on($order->payment->pay_type !== 'wechat', '订单支付方式与退款方式不匹配');
        $refund_no = '40' . microtime(true) * 10000 . mt_rand(1000, 9999);
        $amount = floatval($order->payment->amount) * 100;
        $payment = EasyWeChat::payment();
        $result = $payment->refund->byTransactionId($order->payment->trade_no, $refund_no, $amount, $amount);

        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            return $refund_no;
        } else {
            throw_e($result['err_code_des'] ?? $result['return_msg']);
        }
    }
}
